package com.sping.gobang.service.impl;

import com.sping.gobang.common.util.BeanTransUtils;
//import com.sping.gobang.common.util.JWTUtils;
import com.sping.gobang.common.util.SecurityUtil;
import com.sping.gobang.exception.UserException;
import com.sping.gobang.mapper.UserMapper;
import com.sping.gobang.pojo.datapbject.User;
import com.sping.gobang.pojo.request.UserLoginRequest;
import com.sping.gobang.pojo.request.UserRegisterRequest;
//import com.sping.gobang.pojo.response.UserLoginResponse;
import com.sping.gobang.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(String username,String password) {
        User user1 = userMapper.login(username);
        if(user1==null||user1.getUserId()<1){
//            log.error("查询的用户不存在");
            throw new UserException("查询的用户不存在");
        }
        if(!SecurityUtil.verify(password,user1.getPassword())){
            throw new UserException("用户密码不正确");

        }
        //将userId和username写入载荷
//        Map<String,Object> map=new HashMap<>();
//        map.put("id",user1.getUserId());
//        map.put("name",user1.getUsername());
//        String s= JWTUtils.getJwt(map);
//        return new UserLoginResponse(user1.getUserId(), s);
        return user1;
    }

    @Override
    public boolean register(UserRegisterRequest userRegisterRequest) {
        User user = BeanTransUtils.trans(userRegisterRequest);
        //对密码进行加密
        String encrypt = SecurityUtil.encrypt(user.getPassword());
        user.setPassword(encrypt);
        boolean result=userMapper.register(user);
        return result;
    }

    @Override
    public User getcurrentuser(String currentUsername) {
        User user=userMapper.getcurrentuser(currentUsername);
        if(user==null||user.getUserId()<1){
            throw new UserException("没有找到该用户");
        }
        return user;

    }
}
